﻿using System;
using System.Threading.Tasks;
using System.Threading;

namespace _061.异步方法不等于多线程
{
	internal class Program
	{
		static async Task Main(string[] args)
		{
			Console.WriteLine("之前：" + Thread.CurrentThread.ManagedThreadId);
			double r = await CalcAsync2(500);
			Console.WriteLine($"R={r}");
			Console.WriteLine("之后：" + Thread.CurrentThread.ManagedThreadId);
		}

		/**
		 * 同一个线程执行
		 */
		static async Task<double> CalcAsync(int n)
		{
			Console.WriteLine("CalcAsync-ThreadId:" + Thread.CurrentThread.ManagedThreadId);
			double result = 0;
			Random rand = new Random();
			for (int i = 0; i < n * n; i++)
			{
				result += rand.NextDouble();
			}
			return result;
		}

		/**
		 * 不同的类型执行
		 */
		static async Task<double> CalcAsync2(int n)
		{
			return await Task.Run(() =>
			{
				Console.WriteLine("CalcAsync-ThreadId:" + Thread.CurrentThread.ManagedThreadId);
				double result = 0;
				Random rand = new Random();
				for (int i = 0; i < n * n; i++)
				{
					result += rand.NextDouble();
				}
				return result;
			});
		}

	}
}
